package com.anxin.registerManagement.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.anxin.registerManagement.bean.persist.Finance;
import com.anxin.registerManagement.config.AlipayConfig;
import com.anxin.registerManagement.exception.BusinessException;
import com.anxin.registerManagement.mapper.FinanceMapper;
import com.anxin.registerManagement.util.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author 叶前呈
 * @date 2022/3/20 18:07
 */
@Api(tags = "第三方支付")
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    AlipayConfig alipayConfig;

    @Autowired
    FinanceMapper financeMapper;

    @ApiOperation("支付宝支付接口")
    @PostMapping(value = "/zfb")
    public ResultUtil payController(@RequestParam Integer id) {
        Finance finance = financeMapper.selectOne(new LambdaQueryWrapper<Finance>().eq(Finance::getUserId, id));
        if (ObjectUtils.isEmpty(finance)) {
            throw new BusinessException("财务信息不存在");
        }
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.GATEWAYURL, alipayConfig.APP_ID, alipayConfig.MERCHANT_PRIVATE_KEY, "json", alipayConfig.CHARSET, alipayConfig.ALIPAY_PUBLIC_KEY, alipayConfig.SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.return_url);
        alipayRequest.setNotifyUrl(alipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount = String.valueOf(finance.getMoney());
        //订单名称，必填
        String subject = finance.getOrderName();
        //商品描述，可空
        String body = finance.getOrderDesc();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.success(form);
    }
}
